﻿package net.wangit.dev.version;

import java.util.List;

import net.wangit.Path;
import net.wangit.etl.Extractor;
import net.wangit.jdbc.DBImplementor;
import net.wangit.jdbc.QueryParameters;
import net.wangit.jdbc.util.DBHelper;


public abstract class Version {

	private static final String BATCH_PATH = "batch/";

	public Version() {
	}

	protected abstract String[] getTables();

	protected abstract String[] getSqls();

	protected abstract String getTypeName();

	public void save(int outputMode, String domain, String batchId,
			List<String> ids) throws Exception {
		DBImplementor db = DBHelper.getDomainDB(domain);
		String tables[] = getTables();
		String sqls[] = getSqls();
		for (int i = 0; i < ids.size(); i++) {
			String id = ids.get(i);
			QueryParameters qp = getQueryParameters(id);
			for (int j = 0; j < tables.length; j++) {
				int objectIndex = tables.length <= 1 ? 0 : j + 1;
				String pathPrefix = getPathPrefix(outputMode, domain, batchId,
						id, objectIndex);
				Extractor extractor = new Extractor();
				extractor.extract(db, sqls[j], qp, pathPrefix, tables[j]);
			}

		}

	}

	public boolean check(String domain, String id, String url) throws Exception {
		return true;
	}

	private QueryParameters getQueryParameters(String id) {
		QueryParameters qp = new QueryParameters();
		qp.setValues(new String[] { id });
		qp.setTypes(new int[] { 2 });
		return qp;
	}

	private String getPathPrefix(int outputMode, String domain, String batchId,
			String id, int objectIndex) {
		StringBuffer path = new StringBuffer(Path.getVersionPath());
		if (outputMode == 1)
			path.append(Version.BATCH_PATH).append(batchId).append(".").append(
					domain).append(".").append(getTypeName()).append("/");
		else
			path.append(domain).append("/").append(getTypeName()).append("/")
					.append(id).append("/").append(batchId).append("/");
		path.append(domain).append(".").append(getTypeName()).append(".")
				.append(id).append(".");
		if (objectIndex > 0)
			path.append(objectIndex).append(".");
		path.append(batchId);
		return path.toString();
	}
}
